#! /usr/bin/python3
# -*- coding: utf-8 -*-

# This code shows an example of text translation from English to Simplified-Chinese.
# This code runs on Python 2.7.x and Python 3.x.
# You may install `requests` to run this code: pip install requests
# Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document

import requests
import random
from hashlib import md5
import subprocess
import tkinter.messagebox


def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()


# query = 'Hello World! This is 1st paragraph.\nThis is 2nd paragraph.'
# 处理选择缓冲区中的内容函数：
def inputs():
    # os.popen 执行linux命令，返回输出结果
    cmd = 'xclip -out'
    query_ = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines()
    query = " "
    for i in range(len(query_)):
        query += query_[i].decode('utf-8')  # [b'str...',...]是btype类型的数据，需要转为str普通字符串
    # 结尾是句号的不合并行，结尾不是句号的合并成一句
    query = query.replace(".\n", "\*")
    query = query.replace("\n", " ")
    query = query.replace("\*", ".\n")
    query = query.replace("\r", " ")
    query = query.replace("\t", " ")
    for i in range(8, 2, -1):
        query = query.replace(" " * i, " ")
    query = query.replace("‐ ", "")
    # print(query)
    return query


def shuaxin():
    # 百度翻译api接口所需参数表
    # Set your own appid/appkey.
    appid = '20211105000991769'
    appkey = 'BGMumlXi6QJWE0mmcjCd'

    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    from_lang = 'en'
    to_lang = 'zh'

    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path

    global q0
    q1 = inputs()
    # 当选择缓冲区没有内容或者只有空格符时，跳出本次循环
    if q1 == '' or q1 == ' ':
        pass
    else:
        salt = random.randint(32768, 65536)  # 返回指定范围内的一个整数
        sign = make_md5(appid + q1 + str(salt) + appkey)  # 格式化，使用ytf-8编码
        if len(q0) != len(q1):
            # Generate salt and sign
            # Build request
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
            payload = {'appid': appid, 'q': q1, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

            # Send request
            r = requests.post(url, params=payload, headers=headers)
            result = r.json()
            q0 = q1
            # print(result)
        try:
            # 拼接多个结果，label config
            #  q1 提供的字符串不对时，result会返回错误信息，使用try获取正常值时的指定信息 
            src = '    '
            dst = '    '
            for i in range(len(result['trans_result'])):
                src += result['trans_result'][i]['src'] + '\n    '
                dst += result['trans_result'][i]['dst'] + '\n    '
            lbl.config(text=src)
            lbn.config(text=dst)
        except:
            pass
    lbl.after(1000, shuaxin)


if __name__ == '__main__':
    q0 = '_'  # 记录上一次选择缓冲区的内容
    # 实例化一个窗体——相当于创建窗体对象
    window = tkinter.Tk()
    # 修改窗体名称
    window.title("百度翻译")
    # 设置窗口的宽高和在屏幕上出现的位置，参数是个字符串：宽x高+水平方向位置+垂直方向位置
    # window.geometry("600x500+1200+200")
    window.geometry("+1200+200")  # 没有设置宽高，可以只设置位置。
    # 创建标签控件，参数——对象，字典类型
    lbl = tkinter.Label(window, font=("NotoSansMono Nerd Font", 14), bg="black", fg="white", wraplength=580, anchor='w',
                        justify='left')
    lbl.grid(sticky='nswe')
    lbn = tkinter.Label(window, font=("NotoSansMono Nerd Font", 14), bg="black", fg="white", wraplength=580, anchor='w',
                        justify='left')
    lbn.grid(sticky='nswe')
    # label.after是关键，不阻断进程，循环调取shauxin()
    shuaxin()
    # 界面死循环保持窗口，并监听所有事件
    tkinter.mainloop()
